package chen.jia.xin.finalproject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import chen.jia.xin.finalproject.LogView.LogActivity;

public class BaseActivity extends AppCompatActivity {

    private  ForceOfflineReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Log.d("BaseActivity",getClass().getSimpleName()+"  onCreate");
        ActivityCollector.addActivity(this);

    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("BaseActivity",getClass().getSimpleName()+"  onStart");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("BaseActivity",getClass().getSimpleName()+"  onStop");
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        Log.d("BaseActivity",getClass().getSimpleName()+"  onDestroy");
        ActivityCollector.removeActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("BaseActivity",getClass().getSimpleName()+"  onResume");
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcastbestpractice.FORCE_OFFLINE");
        receiver = new ForceOfflineReceiver();
        registerReceiver(receiver,intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("BaseActivity",getClass().getSimpleName()+"  onPause");
        if(receiver != null){
            unregisterReceiver(receiver);
        }
    }

    class ForceOfflineReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, Intent intent) {
            Log.d("BaseActivity","received");
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("Warning!!!!");
            builder.setMessage("You are gonna be forced to be offline! Are you sure?");
            builder.setCancelable(false);
            builder.setPositiveButton("Sure~", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCollector.finishAll();
                    Intent intent = new Intent(context,LogActivity.class);
                    context.startActivity(intent);
                }
            });
            builder.setNegativeButton("I'm gonna cancel!!", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            builder.show();
        }
    }
}
